package org.leetcode.middle.leetcode22;

import java.util.ArrayList;
import java.util.List;

public class Solution2 {

    List<String> res= new ArrayList<>();

    StringBuilder item = new StringBuilder();
    public List<String> generateParenthesis(int n) {

        backtracking(n,0,0);

        return res;
    }

    private void backtracking(int n,int leftNum,int rightNum){
        if (item.length()==2*n){
            res.add(new String(item));
            return;
        }

        if (leftNum<n){
            item.append("(");
            backtracking(n,leftNum+1,rightNum);
            item.deleteCharAt(item.length()-1);
        }

        if (leftNum>rightNum){
            item.append(")");
            backtracking(n,leftNum,rightNum+1);
            item.deleteCharAt(item.length()-1);
        }

    }
}
